import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbclass } from '../../../../atoms/db';
import Guid from '../../../../atoms/guid';

const logger = anylogger('pages/api/basicinformation/class/update.api');

export type Result = {
	ok: boolean;
	message: string;
};

export type Message = ITbclass;

/**
 * 班级管理-更新数据
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { class_id, ...body } = req.body as Message;
		//#region 验证必填
		if (!body.grade) {
			res.status(200).json({
				ok: false,
				message: '班级届次不能为空'
			});
			return;
		}
		if (!body.majorname) {
			res.status(200).json({
				ok: false,
				message: '班级专业不能为空！'
			});
			return;
		}
		if (!body.classname) {
			res.status(200).json({
				ok: false,
				message: '班级名称不能为空！'
			});
			return;
		}
		//#endregion
		//编辑
		if (class_id) {
			//班级名称是否存在
			const d = await tbclass().select('*').where({
				classname: body.classname
			});
			// if (d.find((it) => { return it.class_id !== class_id; })) {
			// 	res.status(200).json({
			// 		ok: false,
			// 		message: '班级名称不能重复'
			// 	});
			// 	return;
			// }
			await tbclass().update(body).where({
				class_id
			});
		}
		//新增
		else {
			//班级名称是否存在
			const d = await tbclass().first('*').where({
				classname: body.classname
			});
			if (d && d.classname) {
				res.status(200).json({
					ok: false,
					message: '班级名称不能重复'
				});
				return;
			}
			await tbclass().insert({
				...body,
				class_id: Guid()
			});
		}

		res.status(200).json({ ok: true, message: '' });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
